package cn.bugstack.xfg.dev.tech.test;

import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.concurrent.CountDownLatch;
import java.util.zip.GZIPInputStream;

public class OKHttpTest {

    @Test
    public void test_okhttp() throws Exception {

        OkHttpClient client = new OkHttpClient();

        String url = "https://api.zsxq.com/v2/groups/28885518425541/topics?scope=all&count=1";

        Request request = new Request.Builder()
                .url(url)
                .addHeader("Accept-Encoding", "gzip, deflate, br, zstd")
                .addHeader("accept", "application/json, text/plain, */*")
                .addHeader("accept-language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")
                .addHeader("authority", "api.zsxq.com")
                .addHeader("cookie", "zsxq_access_token=E49B3922-5122-4422-BCAC-8C4A2C6214FE_2F994BA247C44F8E; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%22198cb592b399d4-05c4952ce106f4-26061851-1382400-198cb592b3a2c2%22%2C%22first_id%22%3A%22%22%2C%22props%22%3A%7B%7D%2C%22identities%22%3A%22eyIkaWRlbnRpdHlfY29va2llX2lkIjoiMTk4Y2I1OTJiMzk5ZDQtMDVjNDk1MmNlMTA2ZjQtMjYwNjE4NTEtMTM4MjQwMC0xOThjYjU5MmIzYTJjMiJ9%22%2C%22history_login_id%22%3A%7B%22name%22%3A%22%22%2C%22value%22%3A%22%22%7D%2C%22%24device_id%22%3A%22198cb592b399d4-05c4952ce106f4-26061851-1382400-198cb592b3a2c2%22%7D; abtest_env=product")
                .addHeader("dnt", "1")
                .addHeader("origin", "https://wx.zsxq.com")
                .addHeader("referer", "https://wx.zsxq.com/")
                .addHeader("sec-ch-ua", "\"Chromium\";v=\"124\", \"Microsoft Edge\";v=\"124\", \"Not-A.Brand\";v=\"99\"")
                .addHeader("sec-ch-ua-mobile", "?0")
                .addHeader("sec-ch-ua-platform", "\"Windows\"")
                .addHeader("sec-fetch-dest", "empty")
                .addHeader("sec-fetch-mode", "cors")
                .addHeader("sec-fetch-site", "same-site")
                .addHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0")
                .addHeader("x-request-id", "aeb4caf9d-c3f3-fdb9-bcba-7f01305b992")
                .addHeader("x-signature", "7fe8847a8bd78ece71ba4674c641b10ff109ba6b")
                .addHeader("x-timestamp", "1758108827")
                .addHeader("x-version", "2.80.0")
                .build();

        Call call = client.newCall(request);

        // 创建 CountDownLatch 并设置计数为 1
        CountDownLatch latch = new CountDownLatch(1);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
                // 回调失败时也需要释放锁
                latch.countDown();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                ResponseBody responseBody = response.body();
                // 处理gzip压缩的响应体
                String responseBodyStr;
                if ("gzip".equals(response.header("Content-Encoding"))) {
                    try (InputStream is = responseBody.byteStream();
                         GZIPInputStream gzipIs = new GZIPInputStream(is);
                         Reader reader = new InputStreamReader(gzipIs)) {
                        char[] buffer = new char[1024];
                        int len;
                        StringBuilder sb = new StringBuilder();
                        while ((len = reader.read(buffer)) != -1) {
                            sb.append(buffer, 0, len);
                        }
                        responseBodyStr = sb.toString();
                    }
                } else {
                    responseBodyStr = responseBody.string();
                }
                System.out.println("Content-Encoding: " + response.header("Content-Encoding"));
                System.out.println("Response Body: " + responseBodyStr);
                // 回调成功时释放锁
                latch.countDown();
            }
        });

        // 等待回调执行完毕
        latch.await();
    }
}